package com.sgb.jicai.view.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.sgb.jicai.R;
import com.sgb.jicai.base.JiCaiBaseApi;
import com.sgb.jicai.databinding.FragmentJicaiXufangFaqiBinding;
import com.sgb.jicai.view.activity.JiCaiDaTingActivity;
import com.sgb.jicai.viewmodel.JiCaiXuFangFaQiFraModel;
import com.sgb.link.entity.EventConstant;
import com.sgb.link.event.MaterialEvent;
import com.sgb.link.utils.PickCateType;
import com.sgb.jicai.entity.CentralizedMiningEntity;
import com.sgb.jicai.entity.JiCaiHomeListRequestBean;
import com.sgb.jicai.event.JiCaiEventEntity;
import com.sgb.jicai.view.activity.JiCaiSearchTwoActivity;
import com.sgb.jicai.view.adapter.CentralizedMiningCuttingLineAdapter;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;
import com.swgk.core.xrecyclerview.AppBarStateChangeListener;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.CopyUtils;
import com.swgk.core.view.selection.MemberStatusView;
import com.swgk.core.view.selection.XChooseDialog;
import com.swgk.core.view.selection.XChooseEntity;
import com.swgk.core.xrecyclerview.XRecyclerView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;

/**
 * 改造，适应商品-需求大厅
 */
public class JiCaiXuFangFaQiFragment extends AppLazyFragment implements MemberStatusView.OnChooseListener, XChooseDialog.DialogCallBackImpl {
    JiCaiXuFangFaQiFraModel viewModel;
    FragmentJicaiXufangFaqiBinding mBind;
    private static String TYPE = "type";
    /**
     * 参数接收
     */
    public static final String JICAI_TYPE = "JiCaiType";
    private static String JICAI_CLASSIFY = "classify";
    public static final String FROM_WHERE = "FROM_WHERE";
    public static final String KEY_SEARCH_WORDS = "serch";
    private String jicai_classify;
    private int jicaiType;
    private String fromWhere = "";
    private String methodsType = "";
    /**
     * 网络请求对象
     */
    private JiCaiHomeListRequestBean requestBean;
    //适配器
    private CentralizedMiningCuttingLineAdapter centralizedMiningAdapter;
    private LinearLayoutManager layoutManager;
    //搜索内容
    private String keyWords = "";
    //集采范围筛选
    private ThreeLevelAreaWindow mAddressPop;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;
    //集采状态
    private String status = "";
    //集采方式
    private String methods = "";
    //集采范围-省
    private String province = "";
    //集采范围-市
    private String city = "";
    //报价客户
    private String offer = "";
    //加盟客户
    private String joinType = "";

    //侧边筛选
    private SparseArray<String> mNameArray;
    private XChooseDialog mChooseDialog;
    // 数据集
    private SparseArray<XChooseEntity> mData = new SparseArray<>();
    // 本地缓存筛选结果
    private SparseIntArray mFilters = new SparseIntArray();
    private List<CommonPopEntity> types;

    //商品用的东西
    private AppBarLayout.LayoutParams layoutParams;
    private boolean isAppBarExpended = false;
    private static final String TGA = "NewPickSigningUpListFragment";
    private boolean isParentAppBarCollapsed = false;
    private boolean isUpDragging = true;
    /**
     * @param jicaiType 集采类型（二级tab：0全部，1商品集采 2 机械集采 3 设备集采 4 劳务集采 5房产集采 6租赁集采）
     * @param classify  需方发起是1，企业专项是2
     * @return
     */
    public static JiCaiXuFangFaQiFragment newInstance(int jicaiType, String classify, String type, String fromWhere,String serch) {
        JiCaiXuFangFaQiFragment fragment = new JiCaiXuFangFaQiFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(JICAI_TYPE, jicaiType);
        bundle.putString(JICAI_CLASSIFY, classify);
        bundle.putString(TYPE, type);//是否展示集采方式
        bundle.putString(FROM_WHERE, fromWhere);
        bundle.putString(KEY_SEARCH_WORDS, serch);
        fragment.setArguments(bundle);
        return fragment;
    }
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBind = DataBindingUtil.inflate(inflater, R.layout.fragment_jicai_xufang_faqi, container, false);
        viewModel = new ViewModelProvider(this).get(JiCaiXuFangFaQiFraModel.class);
        viewModel.setActivity(JiCaiXuFangFaQiFragment.this);
        requestBean = new JiCaiHomeListRequestBean();
        if (getArguments() != null) {
            //获取传递过来的值
            jicai_classify = getArguments().getString(JICAI_CLASSIFY);
            jicaiType = getArguments().getInt(JICAI_TYPE);
            fromWhere = getArguments().getString(FROM_WHERE);
            methodsType = getArguments().getString(TYPE);
            if (jicai_classify.equals("1")){
                keyWords = getArguments().getString(KEY_SEARCH_WORDS);
            }
        }
        if (methodsType.equals("1")) {
            mBind.jicaiMethods.setVisibility(View.VISIBLE);
        } else {
            mBind.jicaiMethods.setVisibility(View.GONE);
        }
        return mBind.getRoot();
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if ("1".equals(fromWhere)) {
            mBind.include.includeLayout.setVisibility(View.VISIBLE);
        } else if ("0".equals(fromWhere)) {
            mBind.include.includeLayout.setVisibility(View.GONE);
            mBind.imgBackTop.setVisibility(View.GONE);
            mBind.recyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
            mBind.recyclerView.setPullRefreshEnabled(false);
            //initStickView();
        } else {
            mBind.include.includeLayout.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onLazyLoad() {
        //pop数据列表信息请求
        initPopDataList();
        getData();
    }

    public void getData( ) {
        mBind.jicaiMethods.refreshChoose("", "", 0);
        if (jicaiType != 0) {
            mBind.tabLayout.setVisibility(View.VISIBLE);
            viewModel.getTenderGoodsCategoryAllList(PickCateType.TYPE_2, "0", jicaiType + "", false);
        } else {
            mBind.tabLayout.setVisibility(View.GONE);
        }
        initFilterData();
    }

    @Override
    protected void initView() {

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mBind.imgBackTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBind.recyclerView.scrollToPosition(0);
                EventBus.getDefault().post(new JiCaiEventEntity(EventConstant.EVENT_JICAI_TOP_REFRESH_VISIBLE, ""));
            }
        });
        if (centralizedMiningAdapter == null) {
            centralizedMiningAdapter = new CentralizedMiningCuttingLineAdapter(getActivity(), null);
        }
        centralizedMiningAdapter.setOnItemClick(new AdapterOnItemClick<CentralizedMiningEntity>() {
            @Override
            public void onItemClick(CentralizedMiningEntity entity, int position) {
                viewModel.getH5Url(entity.getNo());
            }
        });
        layoutManager = new LinearLayoutManager(getActivity());
        mBind.recyclerView.setLayoutManager(layoutManager);
        //解决数据加载不完的问题
        mBind.recyclerView.setHasFixedSize(true);
        //解决数据加载完成后, 没有停留在顶部的问题
        mBind.recyclerView.setFocusable(false);
        mBind.recyclerView.setAdapter(centralizedMiningAdapter);
        mBind.recyclerView.setLoadingMoreEnabled(true);
        mBind.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                initFilterData();
            }

            @Override
            public void onLoadMore() {
                viewModel.getJiCaiList(requestBean, true);
            }
        });
        mBind.include.tvSearch.setOnClickListener(this);
        //二级tabview处理
        TabLayoutView();
        //筛选按钮点击处理
        optionData();
        //初始化popview
        initializePopView();
    }

    /**
     * 二级tab类目tab点击处理
     */
    private void TabLayoutView() {
        mBind.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (!isPressTabSelect) {
                    return;
                }
                if (tab.getPosition() > 0) {
                    if (types != null && types.size() > 0) {
                        if (types.get(tab.getPosition()) != null) {
                            requestBean.setTypeNo(types.get(tab.getPosition()).getNo());
                        } else {
                            requestBean.setTypeNo("");
                        }
                    }
                } else {
                    requestBean.setTypeNo("");
                }
                mFilters.put(PickCateType.TYPE_2, tab.getPosition());
                updateCategoryData(types.get(tab.getPosition()), tab.getPosition(), false);
                initFilterData();

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    /**
     * 筛选按钮点击处理
     */
    private void optionData() {
        //侧边栏筛选项
        initoptionDataDialog();
        mBind.option.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < mNameArray.size(); i++) {
                    XChooseEntity chooseEntity = mData.get(mData.keyAt(i));
                    if (chooseEntity != null) {
                        if (jicaiType == 0) {
                            if (chooseEntity.getSort() == PickCateType.TYPE_0 ||
                                    chooseEntity.getSort() == PickCateType.TYPE_1 ||
                                    chooseEntity.getSort() == PickCateType.TYPE_6) {
                                if (chooseEntity.getList() == null || chooseEntity.getList().size() == 0) {
                                    initPopDataList();
                                    return;
                                }
                            }
                        } else {
                            if (chooseEntity.getSort() == PickCateType.TYPE_0 ||
                                    chooseEntity.getSort() == PickCateType.TYPE_1 ||
                                    chooseEntity.getSort() == PickCateType.TYPE_2 ||
                                    chooseEntity.getSort() == PickCateType.TYPE_6) {
                                if (chooseEntity.getList() == null || chooseEntity.getList().size() == 0) {
                                    initPopDataList();
                                    return;
                                }
                            }
                        }
                    }
                }
                mChooseDialog.initData(mData, mFilters);
                mChooseDialog.showDialog();
            }
        });
    }

    private void initPopDataList() {
        //集采范围
        if (isListEmpty(PickCateType.TYPE_6)) {
            viewModel.getAddressModel(PickCateType.TYPE_6);
        }
        //集采状态
        if (isListEmpty(PickCateType.TYPE_1)) {
            viewModel.groupBuyClassList(PickCateType.TYPE_1, false);
        }
        //集采方式
        if (methodsType.equals("1")) {
            if (isListEmpty(PickCateType.TYPE_0)) {
                viewModel.getMethodsList(PickCateType.TYPE_0, false);
            }
        }

        //如果是企业专项调用报价客户接口和加盟客户
        if (jicai_classify.equals("2")) {
            if (isListEmpty(PickCateType.TYPE_4)) {
                viewModel.getOfferList(PickCateType.TYPE_4, false);
            }
            if (isListEmpty(PickCateType.TYPE_5)) {
                viewModel.getJoinTypeList(PickCateType.TYPE_5, false);
            }
        }
    }

    private boolean isListEmpty(int catType) {
        return mData.get(catType) != null &&
                (mData.get(catType).getList() == null || mData.get(catType).getList().size() == 0);
    }


    /**
     * 侧边栏筛选项
     */
    private void initoptionDataDialog() {
        mNameArray = new SparseArray<>();
        if (methodsType.equals("1")) {
            mNameArray.put(PickCateType.TYPE_0, "集采方式");
        }
        mNameArray.put(PickCateType.TYPE_1, "集采状态");
        if (jicaiType > 0) {
            switch (jicaiType) {
                case 1:
                    mNameArray.put(PickCateType.TYPE_2, "商品类型");
                    mNameArray.put(PickCateType.TYPE_3, "商品类别");
                    break;
                case 2:
                    mNameArray.put(PickCateType.TYPE_2, "机械类型");
                    mNameArray.put(PickCateType.TYPE_3, "机械类别");
                    break;
                case 3:
                    mNameArray.put(PickCateType.TYPE_2, "设备类型");
                    mNameArray.put(PickCateType.TYPE_3, "设备类别");
                    break;
            }
        }
        if (jicai_classify.equals("2")) {
            mNameArray.put(PickCateType.TYPE_4, "报价客户");
            mNameArray.put(PickCateType.TYPE_5, "加盟客户");
        }
        mNameArray.put(PickCateType.TYPE_6, "省份");
        mNameArray.put(PickCateType.TYPE_7, "市区");
        mChooseDialog = new XChooseDialog(getContext(), mNameArray);
        mChooseDialog.setCallBack(this);
        for (int i = 0; i < mNameArray.size(); i++) {
            int key = mNameArray.keyAt(i);
            addMainEntity(key, new ArrayList<>());
        }
    }

    /**
     * 初始化popview
     */
    private void initializePopView() {
        //集采范围
        initAddressPopup();
        //集采状态
        mBind.jicaiStatus.initPopup(mBind.grayLayout, mBind.popLine, this);
        //集采方式
        mBind.jicaiMethods.initPopup(mBind.grayLayout, mBind.popLine, this);
    }

    //集采范围
    private void initAddressPopup() {
        mBind.jicaiScope.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (scrData == null || scrData.size() == 0) {
                    viewModel.getAddressModel(PickCateType.TYPE_6);
                    return;
                }
                mBind.popLine.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(requestBean.getProvinceNo()) || !TextUtils.isEmpty(requestBean.getCityNo())) {
                    mBind.jicaiScope.updateChooseTextStatus(-2, null);
                } else {
                    mBind.jicaiScope.updateChooseTextStatus(-1, mBind.jicaiScope.getKeyName());
                }
                mAddressPop.showPopwindow0(mBind.popLine);
            }
        });
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setBgView(mBind.grayLayout);
        mAddressPop.setMemberHeight();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(true);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(true);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                province = "";
                city = "";
                requestBean.setProvinceNo(province);
                requestBean.setCityNo(city);
                mFilters.put(PickCateType.TYPE_6, 0);
                addMainEntity(PickCateType.TYPE_7, new ArrayList<>());
                mBind.jicaiScope.updateChooseTextStatus(0, mBind.jicaiScope.getKeyName());
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    province = entity.getProvinceNo();
                    requestBean.setProvinceNo(province);
                    mBind.jicaiScope.updateChooseTextStatus(1, entity.getProvinceName());
                    mFilters.put(PickCateType.TYPE_6, mAddressPop.getProvincePosition());
                    viewModel.getAddressCityData(scrData, province, PickCateType.TYPE_7, false);
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        city = entity.getCityNo();
                        requestBean.setCityNo(city);
                        mBind.jicaiScope.updateChooseTextStatus(1, entity.getCityName());
                        mFilters.put(PickCateType.TYPE_7, mAddressPop.getmCityPosition());
                    }
                }
                //刷新数据
                initFilterData();
            }
        });
        mAddressPop.setOnDismissListener(() -> {
            if (!TextUtils.isEmpty(requestBean.getProvinceNo()) || !TextUtils.isEmpty(requestBean.getCityNo())) {
                mBind.jicaiScope.updateChooseTextStatus(1, null);
            } else {
                mBind.jicaiScope.updateChooseTextStatus(0, mBind.jicaiScope.getKeyName());
            }
        });
    }

    private void addMainEntity(int index, List<CommonPopEntity> list) {
        if (mData.get(index) != null) {
            if (list == null || list.size() == 0) {
                mData.get(index).setList(new ArrayList<>());
            } else {
                mData.get(index).setList(list);
            }
        } else {
            mData.put(index, new XChooseEntity(index, mNameArray.get(index), list));
        }
        mFilters.put(index, 0);
    }

    //列表数据请求
    private void initFilterData() {

        if (getActivity() instanceof JiCaiDaTingActivity){
            keyWords = ((JiCaiDaTingActivity)getActivity()).getKeyWords();
        }else if (getActivity() instanceof JiCaiSearchTwoActivity){
            keyWords = ((JiCaiSearchTwoActivity)getActivity()).getKeyWords();
        }
        requestBean.setSearchKey(keyWords);
        requestBean.setGroupbuyClass(jicaiType == 0 ? "" : String.valueOf(jicaiType));
        if (jicai_classify.equals("1")) {//需方发起
            requestBean.setGroupBuyMode("1");
        } else {
            requestBean.setGroupBuyMode("2");
        }
        switch (methodsType) {
            case "2":
                requestBean.setGroupBuyType("2");
                break;
            case "3":
                requestBean.setGroupBuyType("1");
                break;
        }
        viewModel.getJiCaiList(requestBean, false);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_search) {//搜索点击按钮
            if (!TextUtils.isEmpty(mBind.include.etView.getText().toString())) {
                keyWords = mBind.include.etView.getText().toString();
                initFilterData();
            }
        }
    }

    public void closeRecyclerRefreshing() {
        mBind.recyclerView.refreshComplete();
        mBind.recyclerView.loadMoreComplete();
    }

    /**
     * 列表返回数据
     *
     * @param list
     * @param isLoadMore
     */
    public void setJiCaiList(List<CentralizedMiningEntity> list, boolean isLoadMore) {
        if (isLoadMore) {
            if (list != null && list.size() > 0) {
                centralizedMiningAdapter.addDatas(list);
            } else {
                mBind.recyclerView.setNoMore(true);
            }
        } else {
            if (list != null && list.size() > 0) {
                mBind.emptyView.setVisibility(View.GONE);
                mBind.recyclerView.setVisibility(View.VISIBLE);
                centralizedMiningAdapter.setDatas(list);
                mBind.recyclerView.scrollToPosition(0);
                mBind.recyclerView.setNoMore(false);
            } else {
                centralizedMiningAdapter.clearDatas();
                mBind.emptyView.setVisibility(View.VISIBLE);
                mBind.recyclerView.setVisibility(View.GONE);
            }
        }
    }

    //详情数据跳转链接
    public void showUrl(String url) {
        JiCaiBaseApi.startWeb(getActivity(), url);
    }

    /**
     * //筛选框信息
     *
     * @param type
     * @param data
     */
    public void showLeftDialog(int type, List<CommonPopEntity> data) {
        mChooseDialog.addEntity(type, data);
        mChooseDialog.showDialog();
    }

    //弹窗信息
    public void setChooseItemData(int type, List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) return;
        addMainEntity(type, data);
        switch (type) {
            case PickCateType.TYPE_0://集采方式
                mBind.jicaiMethods.setData(data, methods);
                break;
            case PickCateType.TYPE_1://集采状态
                mBind.jicaiStatus.setData(data, status);
                break;
            case PickCateType.TYPE_2://二级类目
                types = data;
                mBind.tabLayout.removeAllTabs();
                for (CommonPopEntity datum : data) {
                    mBind.tabLayout.addTab(mBind.tabLayout.newTab().setText(datum.getTypeName()));
                }
                requestBean.setTypeNo("");
                tabSelect(0);
                mBind.tabLayout.scrollTo(0, 0);
                break;
            case PickCateType.TYPE_6://省份
                mBind.jicaiScope.setData(data, province);
                break;

        }
    }

    /**
     * 省市区数据信息
     *
     * @param data
     */
    public void setAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (data != null && data.size() > 0) {
            scrData = data;
            mAddressPop.setData(data, true);
        }
    }

    //是否联动
    @Override
    public void loadChildData(XChooseEntity entity, int pos) {
        switch (entity.getSort()) {
            case PickCateType.TYPE_2://二级类目
                updateCategoryData(entity.getList().get(pos), pos, true);
                mChooseDialog.showDialog();
                break;
            case PickCateType.TYPE_6://省份
                updateCityData(entity.getList().get(pos), pos, true);
                mChooseDialog.showDialog();
                break;
            default:
                break;
        }
    }

    private void updateCategoryData(CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        if (isShowLeftDialog) {
            mChooseDialog.addEntity(PickCateType.TYPE_3, new ArrayList<>());
        } else {
            addMainEntity(PickCateType.TYPE_3, new ArrayList<>());
        }

        if (pos > 0) {
            viewModel.getTenderGoodsCategoryAllList(PickCateType.TYPE_3, entity.getNo(), String.valueOf(jicaiType), isShowLeftDialog);
        }
    }

    private void updateCityData(CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        mChooseDialog.addEntity(PickCateType.TYPE_7, new ArrayList<>());
        if (pos > 0) {
            viewModel.getAddressCityData(scrData, entity.getNo(), PickCateType.TYPE_7, isShowLeftDialog);
        }
    }

    //确认
    @Override
    public void result(SparseArray<XChooseEntity> data, SparseIntArray map) {
        mData = CopyUtils.deepPopEntityCopy(data);
        mFilters = map.clone();
        for (int i = 0; i < mData.size(); i++) {
            XChooseEntity entity = mData.get(mData.keyAt(i));
            int key = entity.getSort();
            int value = mFilters.get(key);
            switch (key) {
                case PickCateType.TYPE_0://集采方式
                    methods = entity.getItemNo(value);
                    mBind.jicaiMethods.refreshChoose(methods, entity.getItemName(value), value);
                    requestBean.setGroupBuyType(methods);
                    break;
                case PickCateType.TYPE_1://集采状态
                    status = entity.getItemNo(value);
                    mBind.jicaiStatus.refreshChoose(status, entity.getItemName(value), value);
                    requestBean.setStatus(status);
                    break;
                case PickCateType.TYPE_2://集采二级类目
                    tabSelect(value);
                    requestBean.setTypeNo(entity.getItemNo(value) + "");
                    break;
                case PickCateType.TYPE_3://集采分类
                    if (value > 0) {
                        requestBean.setTypeNo(entity.getItemNo(value) + "");
                    }
                    break;
                case PickCateType.TYPE_4://报价客户
                    if (value > 0) {
                        requestBean.setOfferType(entity.getItemNo(value) + "");
                    }
                    break;
                case PickCateType.TYPE_5://加盟客户
                    if (value > 0) {
                        requestBean.setJoinType(entity.getItemNo(value) + "");
                    }
                    break;
                case PickCateType.TYPE_6://省份
                    requestBean.setProvinceNo(entity.getItemNo(value) + "");
                    province = entity.getItemNo(value);
                    mBind.jicaiScope.refreshChoose(province, entity.getItemName(value), value);
                    mAddressPop.setDefPosition(value, 0);
                    break;
                case PickCateType.TYPE_7://市区
                    requestBean.setCityNo(entity.getItemNo(value) + "");
                    city = entity.getItemNo(value);
                    mAddressPop.setDefPosition(mFilters.get(PickCateType.TYPE_6), value);
                    if (value > 0) {
                        mBind.jicaiScope.refreshChoose(city, entity.getItemName(value), value);
                    }
                    break;
                default:
                    break;
            }
        }
        initFilterData();
    }

    //重置
    @Override
    public void reset() {
        requestBean.setGroupBuyType("");
        requestBean.setStatus("");
        requestBean.setTypeNo("");
        requestBean.setProvinceNo("");
        requestBean.setCityNo("");
        requestBean.setJoinType("");
        requestBean.setOfferType("");
        mFilters.clear();
        resetMainData();
        result(mData, mFilters);
        mChooseDialog.initData(mData, mFilters);
        mChooseDialog.showDialog();
    }

    private void resetMainData() {
        addMainEntity(PickCateType.TYPE_3, new ArrayList<>());
        addMainEntity(PickCateType.TYPE_7, new ArrayList<>());
        if (fromWhere.equals("2")) {
            mBind.tabLayout.scrollTo(0, 0);
            tabSelect(0);
            requestBean.setTypeNo("");
        }
    }


    private boolean isPressTabSelect;

    private void tabSelect(int pos) {
        isPressTabSelect = false;
        if (mBind.tabLayout.getTabCount() > 0) {
            mBind.tabLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mBind.tabLayout.getTabAt(pos).select();
                    isPressTabSelect = true;
                }
            }, 80);
        }
    }

    //取消
    @Override
    public void onCancel() {
        mChooseDialog.initData(mData, mFilters);
    }

    //pop初始化数据
    @Override
    public void onLoadChooseData(String mKeyName) {
        switch (mKeyName) {
            case "集采方式":
                viewModel.getMethodsList(PickCateType.TYPE_0, false);
                break;
            case "集采状态":
                viewModel.groupBuyClassList(PickCateType.TYPE_1, false);
                break;
            case "报价客户":
                viewModel.getOfferList(PickCateType.TYPE_4, false);
                break;
            case "加盟客户":
                viewModel.getJoinTypeList(PickCateType.TYPE_5, false);
                break;
        }
    }

    //pop点击事件
    @Override
    public void onChooseResult(String mKeyName, CommonPopEntity entity, Object... objects) {
        int position = (int) objects[0];
        String no = position == 0 ? "" : entity.getNo();
        String id = position == 0 ? "" : entity.getId();
        String name = position == 0 ? "" : entity.getTypeName();
        switch (mKeyName) {
            case "集采方式":
                if (!TextUtils.equals(no, methods)) {
                    methods = no;
                    requestBean.setGroupBuyType(methods);
                    mFilters.put(PickCateType.TYPE_0, position);
                    initFilterData();
                }
                break;
            case "集采状态":
                if (!TextUtils.equals(no, status)) {
                    status = no;
                    requestBean.setStatus(status);
                    mFilters.put(PickCateType.TYPE_1, position);
                    initFilterData();
                }
                break;
            case "报价客户":
                if (!TextUtils.equals(no, offer)) {
                    offer = no;
                    requestBean.setOfferType(offer);
                    mFilters.put(PickCateType.TYPE_4, position);
                    initFilterData();
                }
                break;
            case "加盟客户":
                if (!TextUtils.equals(no, joinType)) {
                    joinType = no;
                    requestBean.setJoinType(joinType);
                    mFilters.put(PickCateType.TYPE_5, position);
                    initFilterData();
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(JiCaiEventEntity event) {
        if (event.getCode() == EventConstant.EVENT_JICAI_HOME_FOUR_TYPE_SEARCH) {
            keyWords = event.getName();
            initFilterData();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(MaterialEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_APPBAR_STATE_EXPANDED) {
            if (layoutParams != null) {
                layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
                mBind.llContainer.setLayoutParams(layoutParams);
                isParentAppBarCollapsed = false;
            }
        } else if (event.getMessageTag() == EventConstant.EVENT_APPBAR_STATE_COLLAPSED) {
            if (layoutParams != null) {
//                layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
//                binding.llContainer.setLayoutParams(layoutParams);
                isParentAppBarCollapsed = true;
            }
        } else if (event.getMessageTag() == EventConstant.EVENT_APPBAR_STATE_COMMON) {
            if (layoutParams != null) {
                layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
                mBind.llContainer.setLayoutParams(layoutParams);
                isParentAppBarCollapsed = false;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /****
     * 初始化置顶监听（商品用的东西）
     */
    private void initStickView() {
        layoutParams = (AppBarLayout.LayoutParams) mBind.llContainer.getLayoutParams();
        mBind.appBar.addOnOffsetChangedListener(new AppBarStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                if (state == State.EXPANDED) {
                    isAppBarExpended = true;
                } else {
                    isAppBarExpended = false;
                }
            }
        });
        mBind.appBar.post(() -> {
            CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) mBind.appBar.getLayoutParams();
            AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) layoutParams.getBehavior();
            if (behavior != null) {
                behavior.setDragCallback(new AppBarLayout.Behavior.DragCallback() {
                    @Override
                    public boolean canDrag(@NonNull AppBarLayout appBarLayout) {
                        return true;
                    }
                });
            }
        });
        mBind.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (layoutManager != null) {
                    int completelyVisibleItemPosition = layoutManager.findFirstCompletelyVisibleItemPosition();
                    if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                        if (completelyVisibleItemPosition == 0) {
                            if (!isParentAppBarCollapsed) {
                                layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
                            } else {
                                if (isAppBarExpended) {
                                    if (!isUpDragging) {
                                        layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
                                    } else {
                                        layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
                                    }
                                } else {
                                    layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
                                }
                            }
                            mBind.llContainer.setLayoutParams(layoutParams);
                            mBind.llContainer.requestLayout();
                        } else {
                            if (isParentAppBarCollapsed && isAppBarExpended) {
                                if (isUpDragging) {
                                    layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
                                } else {
                                    layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
                                }
                                mBind.llContainer.setLayoutParams(layoutParams);
                                mBind.llContainer.requestLayout();
                            }
                        }
                    }
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (dy > 0) {
                    if (isParentAppBarCollapsed) {
                        if (isAppBarExpended) {
                            if (isUpDragging) {
                                layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
                            } else {
                                if (layoutParams.getScrollFlags() != 0) {
                                    layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
                                } else {
                                    layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
                                }
                            }
                            mBind.llContainer.setLayoutParams(layoutParams);
                            mBind.llContainer.requestLayout();
                        }
                    } else {
                        layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
                        mBind.llContainer.setLayoutParams(layoutParams);
                        mBind.llContainer.requestLayout();
                    }
                    isUpDragging = true;
                } else if (dy < 0) {
                    if (isParentAppBarCollapsed) {
                        if (isAppBarExpended) {
                            if (!isUpDragging) {
                                layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
                            } else {
                                if (layoutParams.getScrollFlags() != 0) {
                                    layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
                                } else {
                                    layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
                                }
                            }
                            mBind.llContainer.setLayoutParams(layoutParams);
                            mBind.llContainer.requestLayout();
                        }
                    } else {
                        layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
                        mBind.llContainer.setLayoutParams(layoutParams);
                        mBind.llContainer.requestLayout();
                    }
                    isUpDragging = false;
                }
            }
        });
    }

    //重置数据信息
    public void initializePop() {
        province = "";
        city = "";
        requestBean.setGroupBuyType("");
        requestBean.setStatus("");
        requestBean.setTypeNo("");
        requestBean.setProvinceNo("");
        requestBean.setCityNo("");
        initAddressPopup();
        if (scrData != null && scrData.size() > 0) {
            mAddressPop.setData(scrData, true);
        }
        mFilters.clear();
        resetMainData();
        result(mData, mFilters);
        mChooseDialog.initData(mData, mFilters);
        mBind.jicaiScope.refreshChoose("", "", 0);
        mAddressPop.setDefPosition(0, 0);
    }
}
